package leetcode.editor.cn;

import java.util.Arrays;

public class P462MinimumMovesToEqualArrayElementsIi {
    public static void main(String[] args) {
        Solution solution = new P462MinimumMovesToEqualArrayElementsIi().new Solution();

    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public int minMoves2(int[] nums) {
            int length = nums.length;
            Arrays.sort(nums);
            int midValue = nums[(length + 1) / 2 - 1];
            if ((length & 1) == 0) {
                midValue = (nums[length / 2 - 1] + nums[length / 2]) / 2;
            }
            int sum = 0;
            for (int num : nums) {
                sum += Math.abs(num - midValue);
            }
            return sum;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}